package com.example.weixinsystem.controller;

import com.example.weixincommonlog.annotation.WxLog;
import com.example.weixincommonlog.enums.BusinessType;
import com.example.weixinsystem.service.LoginService;
import com.example.weixinsystem.service.SysUserService;
import com.weixin.common.core.domain.Result;
import com.weixin.common.core.form.LoginForm;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;

/**
 * 登录接口
 *
 * @version 1.0.0
 * @className: UserController
 * @description: 登录接口
 * @author: zhangjunfa
 * @date: 2023/5/27 11:59
 */
@Slf4j
@RestController
@RequestMapping
public class LoginController {
    private final LoginService loginService;
    private final SysUserService sysUserService;

    public LoginController(LoginService loginService, SysUserService sysUserService) {
        this.loginService = loginService;
        this.sysUserService = sysUserService;
    }

    /**
     * 登录
     *
     * @param loginForm 登录参数
     * @return 返回Token
     */
    @PostMapping("/login")
    @WxLog(title = "用户登录",type = BusinessType.OTHER)
    public Result<?> login(@Validated LoginForm loginForm) {
        String token = this.loginService.login(loginForm);
        return Result.ok(token);
    }

    /**
     * 退出登录
     *
     * @param request 请求头
     * @return
     */
    @PostMapping("/logout")
    @WxLog(title = "退出登录",type = BusinessType.OTHER)
    public Result<?> logout(HttpServletRequest request) {
        this.loginService.logout(request);
        return Result.ok();
    }

    /**
     * 刷新Token
     *
     * @param request 请求头
     * @return 返回成功
     */
    @PostMapping("/refreshToken")
    @WxLog(title = "刷新Token",type = BusinessType.OTHER)
    public Result<?> refreshToken(HttpServletRequest request) {
        loginService.refreshToken(request);
        return Result.ok();
    }

    /**
     * 注册
     *
     * @param loginForm 注册必填项
     * @return 成功
     */
    @PostMapping("/register")
    @WxLog(title = "用户注册",type = BusinessType.ADD)
    public Result<?> register(@Validated LoginForm loginForm) {
        sysUserService.addUser(loginForm);
        return Result.ok();
    }

}
